package com.hsj.goldstore.mvp.present;

import android.text.TextUtils;

import com.hsj.goldstore.base.BaseMvpPresent;
import com.hsj.goldstore.base.ResultCallback;
import com.hsj.goldstore.bean.LoginBean;
import com.hsj.goldstore.mvp.model.LoginModel;
import com.hsj.goldstore.mvp.view.LoginView;

/**
 * Created by Administrator on 2018/3/25.
 */

public class LoginPresent extends BaseMvpPresent<LoginView> implements ILoginPresent {

    private LoginModel loginModel;
    private String phone;
    private String pwd;

    public LoginPresent() {
        this.loginModel = new LoginModel();
    }

    @Override
    public void init() {
        checkViewAttach();
        mvpView.showUserInfo();
    }

    @Override
    public void login() {
        if (checkInputEmpty()) return;
        requestLogin();
    }

    /**
     * 登录请求
     */
    private void requestLogin() {
        mvpView.showProgress("请稍等...");
        loginModel.login(phone, pwd, new ResultCallback() {
                        @Override
                        public void onSuccess(Object data, int code, String msg) {
                            mvpView.hideProgress();
                            LoginBean loginBean = (LoginBean) data;
                            mvpView.saveUserInfo(phone,pwd,loginBean);
                            mvpView.showError("登录成功");
                            mvpView.gotoMainActivity();
                        }

            @Override
            public void onFalure(int code, String err) {
                mvpView.hideProgress();
                mvpView.showError(err);
            }
        });
    }

    /**
     * @return 检查 是否填写手机号和密码
     * true 表示已填写
     * false 其他
     */
    private boolean checkInputEmpty() {
        phone = mvpView.getPhone();
        pwd = mvpView.getPWD();
        if (TextUtils.isEmpty(phone)) {
            mvpView.showError("请输入手机号");
            return true;
        }
        if (TextUtils.isEmpty(pwd)) {
            mvpView.showError("请输入密码");
            return true;
        }
        if (pwd.length() < 6 || pwd.length() > 12) {
            mvpView.showError("密码必须大于6位小于12位");
            return true;
        }

        return false;
    }
}
